package com.gpay.erp.web.control;

import com.gpay.erp.core.dao.page.PageHelper;
import com.gpay.erp.core.dao.page.PagerModel;
import com.gpay.erp.core.system.bean.SysUser;
import com.gpay.erp.services.common.GlobalStatus;
import com.gpay.erp.services.purchase.ContractService;
import com.gpay.erp.services.purchase.PaidApplicationService;
import com.gpay.erp.services.purchase.PaidApplicationSubService;
import com.gpay.erp.services.purchase.bean.Contract;
import com.gpay.erp.services.purchase.bean.PaidApplication;
import com.gpay.erp.services.purchase.bean.PaidApplicationSub;
import com.gpay.erp.web.util.Arith;
import com.gpay.erp.web.util.WebUtil;
import com.gpay.erp.web.vo.ChangeStatus;
import com.gpay.erp.web.vo.PaidApplicationDelete;
import com.gpay.erp.web.vo.PaidApplicationMode;
import com.gpay.erp.web.vo.ResponseInfo;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.support.RequestContext;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by wuzonghui on 15/11/5.
 */
@Controller
@RequestMapping("/payment/")
public class PaymentAppController extends BaseController {
    private Log logger = LogFactory.getLog(ApplicationController.class);
    @Autowired
    private PaidApplicationService paidApplicationService;
    @Autowired
    private PaidApplicationSubService paidApplicationSubService;
    @Autowired
    private GlobalStatus globalStatus;
    @Autowired
    private ContractService contractService;



    // 页面跳转 付款申请页面
    @RequestMapping("paymentApList")
    public String paymentApList() {
        return "purchase/paymentApList";
    }

    // 页面跳转 付款申请明细页面
    @RequestMapping("paymentUpdate")
    public String paymentUpdate(String id, ModelMap modelMap) {
        modelMap.addAttribute("paymentApId", id);
        return "purchase/paymentApAdd";
    }

    // 页面跳转 付款申请新增
    @RequestMapping("paymentApAdd")
    public String paymentApAdd() {
        return "purchase/paymentApAdd";
    }

    @RequestMapping("paymentApAddSub" )
    public String paymentApAddSub(String id, ModelMap modelMap) {
        modelMap.addAttribute("supplierId", id);
        return "purchase/paymentApAddSub";
    }

    // 页面跳转 付款申请审批
    @RequestMapping("paymentApCheckList")
    public String checkList() {
        return "purchase/paymentApCheckList";
    }

    // 页面跳转 审批明细
    @RequestMapping("paymentApView")
    public String paymentApView(String id, ModelMap modelMap) {
        modelMap.addAttribute("paymentApId", id);
        return "purchase/paymentApView";
    }

    /**
     * 付款申请查询 返回单表list
     */
    @RequestMapping("selectPagePaidApplicationList")
    public void selectPagePaidApplicationList(PaidApplication paidApplication, PageHelper pageHelper,
                                              HttpServletRequest request, HttpServletResponse response) {
        logger.info("selectPagePaidApplicationList start");
        if("".equals(pageHelper.getOrder())||null == pageHelper.getOrder())
        {
            pageHelper.setOrder("id");
            pageHelper.setSort("desc");
        }
        paidApplication.setFromRow((pageHelper.getPage() - 1) * pageHelper.getRows());
        paidApplication.setToRow(pageHelper.getPage() * pageHelper.getRows());
        paidApplication.setSort(pageHelper.getSort());
        paidApplication.setOrder(pageHelper.getOrder());
        PagerModel pagerModel = paidApplicationService.selectPageList(paidApplication);
        deplayInfor(pagerModel,request,response);
    }
    /**
     * 添加付款申请子项 点击  付款申请生成  修改保存都是调用次方法
     * 对三张表操作
     * 1.付款申请主表插入一条主表信息
     * 2.付款申请子表插入一条信息 申请金额,总金额=含税货款金额-实付金额
     * 3.修改合同主表付款申请中金额,以及总金额 总金额=含税货款金额-申请中金额;申请中金额每次都加
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping("savePaidApplicationSub")
    public void savePaidApplicationSub(@RequestBody PaidApplicationMode paidApplicationMode,
                                HttpServletRequest request, HttpServletResponse response) {
        logger.info("savePaidApplicationSub start");
        RequestContext requestContext = new RequestContext(request);
        ResponseInfo responseInfo = new ResponseInfo();
        HttpSession session = request.getSession();
        SysUser sysUser = (SysUser) session.getAttribute("loginUser");
        int insertId =1;
        if (paidApplicationMode != null) {
            //组织付款申请主表数据
            PaidApplication paidApplication = paidApplicationMode.getPaidApplication();
            if (null == paidApplication.getPaidAppNumber()||"".equals(paidApplication.getPaidAppNumber())){
                String paidCode =paidApplicationService.getPaidApplicationCode();
                paidApplication.setPaidAppNumber(paidCode); //生成付款申请号
                paidApplication.setRealAmount(0.0);
            }

            if ("".equals(paidApplication.getPaidStatus())||null == paidApplication.getPaidStatus()){
                paidApplication.setPaidStatus("1"); //付款申请状态状态
            }

            paidApplication.setAccountName(sysUser.getAccountName());
            paidApplication.setF_account(sysUser.getF_account());
            //组织付款申请子项数据
            List<PaidApplicationSub> paidApplicationSubList = paidApplicationMode.getPaidApplicationSubList();
            for(PaidApplicationSub paidApplicationSub:paidApplicationSubList)
            {
//                Double taxAmount =0.0; //含税货款金额
//                if (null !=paidApplicationSub.getTaxAmount() ){
//                    taxAmount = paidApplicationSub.getTaxAmount();
//                }
//                Double paidAmount =0.0; //实付金额
//                if (null !=paidApplicationSub.getPaidAmount() ){
//                    paidAmount = paidApplicationSub.getPaidAmount();
//                }
//
//                paidApplicationSub.setPaidAppNum(paidApplication.getPaidAppNumber());
//                paidApplicationSub.setTotalAmount(Arith.sub(taxAmount,paidAmount));//付款申请 总金额
//                paidApplicationSub.setPaidAmount(paidAmount);
                paidApplicationSub.setAccountName(sysUser.getAccountName());
                paidApplicationSub.setF_account(sysUser.getF_account());
            }
            if ("".equals(paidApplication.getId())||null == paidApplication.getId())  //新增保存
            {
                insertId = paidApplicationService.savePaidApplicationSubList(paidApplication,paidApplicationSubList,getContractAllAmount(paidApplicationSubList)); //数据库保存

            }else { //修改保存
                String status = paidApplicationService.selectById(paidApplication.getId()).getPaidStatus();//当前状态
                PaidApplicationSub paidApplicationSub = new PaidApplicationSub();
                paidApplicationSub.setF_paidId(paidApplication.getId());
                List<PaidApplicationSub> paidApplicationSubList1 = paidApplicationSubService.selectList(paidApplicationSub);
                paidApplication.setPaidStatus("1"); //
                if("1".equals(status)||"3".equals(status)) { //新增和审核不通过可以修改保存
                    List<Contract> contractList = deleteContractAllAmount(paidApplicationSubList1);
                        insertId = paidApplicationService.saveUpdatePaidApplicationSub(paidApplication,paidApplicationSubList,contractList,getContractAllAmount(paidApplicationSubList)); //数据库保存
                }else {
                    responseInfo.setResult("20001");
                    responseInfo.setMessage(requestContext.getMessage("application.service.fail"));
                    responseInfo.setObject("1");
                    WebUtil.responseToJson(response, responseInfo);
                }

            }
        }
        if (insertId != 1) {
            try {
                selectPaidApplicationSub(String.valueOf(insertId), request, response);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        logger.info("savePaidApplicationSub end");
    }
    /**
     * 付款申请生成并提交
     * 调用新增并保存方法
     */
    @RequestMapping("saveCommitPaidApplicationSub")
    public void saveCommitPaidApplicationSub(@RequestBody PaidApplicationMode paidApplicationMode,
                                             HttpServletRequest request, HttpServletResponse response){

        paidApplicationMode.getPaidApplication().setPaidStatus("2"); //保存并提交
        savePaidApplicationSub(paidApplicationMode,request,response);
    }


    /**
     * 添加合同申请金额 和总金额
     * @param list
     * @return
     */
    public List<Contract> getContractAllAmount(List<PaidApplicationSub> list) {
        List<Contract> contractList = new ArrayList<Contract>();
        for (PaidApplicationSub paidApplicationSub:list){

            Contract contract = contractService.selectById(paidApplicationSub.getF_contractId());

            Double appcAmount =0.0; //合同申请金额
            if (contract.getAmountApplication() != null){
                appcAmount = contract.getAmountApplication();
            }
            Double appPaidAmount =0.0; //付款子项申请金额
            if (null !=paidApplicationSub.getAppBalance()){
                appPaidAmount = paidApplicationSub.getAppBalance();
            }
            Double appAmount = Arith.add(appcAmount,appPaidAmount);//合同申请中金额
            contract.setAmountApplication(appAmount); //修改申请中金额
//            Double taxGoodsAmount = 0.0;
//            if(null !=contract.getTaxGoodsAmount()){
//                taxGoodsAmount = contract.getTaxGoodsAmount();
//            }
//            Double totalMount = Arith.sub(taxGoodsAmount,appAmount);//合同总金额
//            contract.setTotalAmount(totalMount);
            contract.setAmountPaid(0.0);
            contractList.add(contract);
        }
        return  contractList;
    }

    /**
     * 删除合同申请金额和 总金额
     * @param list
     * @return
     */
    public List<Contract> deleteContractAllAmount(List<PaidApplicationSub> list) {
        List<Contract> contractList = new ArrayList<Contract>();
        for (PaidApplicationSub paidApplicationSub:list){

            Contract contract = contractService.selectById(paidApplicationSub.getF_contractId());

            Double appcAmount =0.0; //合同申请金额
            if (contract.getAmountApplication() != null){
                appcAmount = contract.getAmountApplication();
            }
            Double appPaidAmount =0.0; //付款子项申请金额
            if (null !=paidApplicationSub.getAppBalance()){
                appPaidAmount = paidApplicationSub.getAppBalance();
            }
            Double appAmount = Arith.sub(appcAmount,appPaidAmount);//合同申请中金额
            contract.setAmountApplication(appAmount); //修改申请中金额
//            Double taxGoodsAmount = 0.0;
//            if(null !=contract.getTaxGoodsAmount()){
//                taxGoodsAmount = contract.getTaxGoodsAmount();
//            }
//            Double totalMount = Arith.sub(taxGoodsAmount,appAmount);//合同总金额
//            contract.setTotalAmount(totalMount);
            contract.setAmountPaid(0.0);
            contractList.add(contract);
        }
        return  contractList;
    }

    /**
     * 点击付款申请子项详细查询
     * @param id 采购申请id
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping("selectPaidApplicationSub")
    public void selectPaidApplicationSub(String id,
                                  HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        logger.info("selectPaidApplicationSub start");
        RequestContext requestContext = new RequestContext(request);
        ResponseInfo responseInfo = new ResponseInfo();
        if (id == null) {
            id = "1";
        }
        PaidApplication paidApplication = paidApplicationService.selectById(id);
        String statusCode = globalStatus.getPaidApplicationStatus(Integer.parseInt(paidApplication.getPaidStatus()));
        paidApplication.setPaidStatus(statusCode);
        PaidApplicationSub paidApplicationSub = new PaidApplicationSub();
        paidApplicationSub.setF_paidId(id);
        List<PaidApplicationSub> listA = paidApplicationSubService.selectList(paidApplicationSub);
        PaidApplicationMode paidApplicationMode = new PaidApplicationMode();
        paidApplicationMode.setPaidApplication(paidApplication);
        paidApplicationMode.setPaidApplicationSubList(listA);
        String result = "";
        String message = "";
        if (listA != null) {
            result = "00010";
            message = requestContext.getMessage("select.success");

        } else {
            result = "11111";
            message = requestContext.getMessage("no.data");

        }
        responseInfo.setResult(result);
        responseInfo.setMessage(message);
        responseInfo.setObject(paidApplicationMode);
        logger.info("selectPaidApplicationSub end");
        WebUtil.responseToJson(response, responseInfo);
    }
    /**
     * 付款申请详情 点击删除一行记录
     */
    @RequestMapping("deleteOnePaidApplicationSub")
    public void deleteOnePaidApplicationSub(@RequestBody PaidApplicationDelete paidApplicationDelete,
                                        HttpServletRequest request, HttpServletResponse response) {
        logger.info("deleteOnePaidApplicationSub start");
        RequestContext requestContext = new RequestContext(request);
        ResponseInfo responseInfo = new ResponseInfo();
        int updateId = 1;
        String status = paidApplicationService.selectById(paidApplicationDelete.getPaidApplicationId()).getPaidStatus();//当前状态
        List<PaidApplicationSub> paidApplicationSubList =new ArrayList<PaidApplicationSub>();
        if ("1".equals(status)||"3".equals(status)) {
            for (String subId : paidApplicationDelete.getPaidApplicationSubIds()) {
                PaidApplicationSub paidApplicationSub = paidApplicationSubService.selectById(subId);
                paidApplicationSubList.add(paidApplicationSub);
            }
            List<Contract> contractList = deleteContractAllAmount(paidApplicationSubList); //组织合同数据
            updateId = paidApplicationService.deleteOnePaidApplicationSub(paidApplicationDelete.getPaidApplicationId(),paidApplicationDelete.getPaidApplicationSubIds(),contractList);
            if (updateId !=1)
            {
                try {
                    selectPaidApplicationSub(paidApplicationDelete.getPaidApplicationId(), request,response);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } else {
            responseInfo.setResult("00041");
            responseInfo.setMessage(requestContext.getMessage("application.service.fail"));
            responseInfo.setObject(updateId);
            WebUtil.responseToJson(response, responseInfo);
        }
        logger.info("deleteOnePaidApplicationSub end");
    }

    /**
     * 付款申请详细子页面
     *
     * @param changeStatus 审批通过 passApp status 4;
     *                     拒绝  审批不通过 passnotApp status 3;
     *                     撤销审批   cancelCheck status 2;
     *                     手工提交 commitApp status 2;
     *                     撤销提交 cancelcommitApp status 1;
     *                     撤销申请 cancelApp status 0
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping("saveChangeStatusApplicationSub")
    public void saveChangeStatusApplicationSub(@RequestBody ChangeStatus changeStatus,
                                         HttpServletRequest request, HttpServletResponse response) {
        logger.info("saveChangeStatusApplicationSub start");
        RequestContext requestContext = new RequestContext(request);
        ResponseInfo responseInfo = new ResponseInfo();
        String id = changeStatus.getId();
        int updateId = 1;
        String status = paidApplicationService.selectById(changeStatus.getId()).getPaidStatus();//当前状态
        if ("commitApp".equals(changeStatus.getStatus())){
            if ("1".equals(status)){ //只有新增状态才能提交
                updateId = paidApplicationService.updateCommitPaidAppStatus(id,"2");
            }
        }else if("cancelcommitApp".equals(changeStatus.getStatus())) {
            if ("2".equals(status)) { //只有提交状态才能撤销提交
                updateId =paidApplicationService.updateCommitPaidAppStatus(id,"1");
            }
        }else if ("passApp".equals(changeStatus.getStatus())) {
            if ("2".equals(status)) { //只有提交状态才能审核通过
                updateId =paidApplicationService.updateCommitPaidAppStatus(id,"4");
            }
        }else if ("passnotApp".equals(changeStatus.getStatus())) {
            if ("2".equals(status)) {//只有提交状态才能审核不通
                updateId =paidApplicationService.updateCommitPaidAppStatus(id,"3");
            }
        }else if ("cancelCheck".equals(changeStatus.getStatus())) {
            if ("4".equals(status)) { //只有审核通过才能 撤销审批
                updateId = paidApplicationService.updateCommitPaidAppStatus(id, "2");
            }
        }else if ("cancelApp".equals(changeStatus.getStatus())) {
            if ("1".equals(status)||"3".equals(status)){

                PaidApplicationSub paidApplicationSub1 = new PaidApplicationSub();
                paidApplicationSub1.setF_paidId(id);
                List<PaidApplicationSub> paidApplicationSubList = paidApplicationSubService.selectList(paidApplicationSub1);
                List<Contract> contractList = deleteContractAllAmount(paidApplicationSubList);

                updateId = paidApplicationService.updatePaidApplicationSubList(id,"0",contractList); //数据库保存
            }

        }


        if(updateId != 1) {
                try {
                    selectPaidApplicationSub(changeStatus.getId(), request, response);
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }else {
            responseInfo.setResult("20001");
            responseInfo.setMessage(requestContext.getMessage("application.service.fail"));
            responseInfo.setObject("1");
            WebUtil.responseToJson(response, responseInfo);
        }
        logger.info("saveChangeStatusApplicationSub end");
    }
    /**
     * 付款申请审核 返回单表list
     * @param paidApplication
     * @param pageHelper
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping("selectPageCheckPaidApplicationList")
    public void selectPageCheckPaidApplicationList(PaidApplication paidApplication, PageHelper pageHelper,
                                              HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        logger.info("selectPageCheckPaidApplicationList start");

        if("".equals(pageHelper.getOrder())||null == pageHelper.getOrder())
        {
            pageHelper.setOrder("id");
            pageHelper.setSort("desc");
        }
        paidApplication.setFromRow((pageHelper.getPage() - 1) * pageHelper.getRows());
        paidApplication.setToRow(pageHelper.getPage() * pageHelper.getRows());
        if (paidApplication.getPaidStatus() == null){
            paidApplication.setPaidStatus("2");
        }
        paidApplication.setSort(pageHelper.getSort());
        paidApplication.setOrder(pageHelper.getOrder());
        PagerModel pagerModel = paidApplicationService.selectPageList(paidApplication);
        deplayInfor(pagerModel,request,response);
        logger.info("selectPageCheckPaidApplicationList end");
    }

    /**
     * 付款订单 返回单表list
     * @param paidApplication
     * @param pageHelper
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping("selectPaymentOrderList")
    public void selectPaymentOrderList(PaidApplication paidApplication, PageHelper pageHelper,
                                                   HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        logger.info("selectPaymentOrderList start");

        if("".equals(pageHelper.getOrder())||null == pageHelper.getOrder())
        {
            pageHelper.setOrder("id");
            pageHelper.setSort("desc");
        }
        paidApplication.setFromRow((pageHelper.getPage() - 1) * pageHelper.getRows());
        paidApplication.setToRow(pageHelper.getPage() * pageHelper.getRows());
        if (paidApplication.getPaidStatus() == null){
            paidApplication.setPaidStatus("4");
        }
        paidApplication.setSort(pageHelper.getSort());
        paidApplication.setOrder(pageHelper.getOrder());
        PagerModel pagerModel = paidApplicationService.selectPageList(paidApplication);
        deplayInfor(pagerModel,request,response);
        logger.info("selectPaymentOrderList end");
    }
    /**
     * 页面显示的信息
     * @param pagerModel
     * @param request
     * @param response
     */
    public void deplayInfor(PagerModel pagerModel,HttpServletRequest request, HttpServletResponse response) {
        RequestContext requestContext = new RequestContext(request);
        ResponseInfo responseInfo = new ResponseInfo();
        if (pagerModel != null) {
            for (Object hashMap1 : pagerModel.getRows()) {
                PaidApplication hashMap = (PaidApplication) hashMap1;
                String statusCode = globalStatus.getPaidApplicationStatus(Integer.parseInt(hashMap.getPaidStatus()));
                if (null != hashMap.getCurrencyCode()) {
                    String currency = globalStatus.getCurrencys(Integer.parseInt(hashMap.getCurrencyCode()));
                    hashMap.setCurrencyCode(currency);
                }
                if (null != hashMap.getPayMethod()) {
                    String payMethod = globalStatus.getPayMethod(Integer.parseInt(hashMap.getPayMethod()));
                    hashMap.setPayMethod(payMethod);
                }

                hashMap.setPaidStatus(statusCode);

            }
            responseInfo.setResult("00010");
            responseInfo
                    .setMessage(requestContext.getMessage("select.success"));
            responseInfo.setObject(pagerModel);
        } else {
            responseInfo.setResult("11111");
            responseInfo.setMessage(requestContext.getMessage("no.data"));
            responseInfo.setObject("1");
        }

        WebUtil.responseToJson(response, responseInfo);
    }
}
